package com.example.leetcode.trainingcamp.week1.practice1;

public class Offer67 {

    public int strToInt(String str) {
        long res = 0;
        int n = str.length(), ans = 1;
        int head = 0;
        while (head < n && str.charAt(head) == ' ')
            head++;
        if (head == n)
            return 0;
        //处理首字符
        char h = str.charAt(head);
        if (h != '+' && h != '-' && (h > '9' || h < '0')) {
            return 0;
        }
        //处理正负号
        if (h == '-')
            ans = -ans;
        //当首字符是数字，就可以不用判断下一个字符，如果是符号，则应继续判断
        if (h >= '0' && h <= '9')
            res += (h - '0');
        else if (head == n - 1 || str.charAt(head + 1) < '0' || str.charAt(head + 1) > '9')
            return 0;
        //获得数字，注意判断是否超范围，利用long 以及 符号是否为正负
        for (int i = head + 1; i < n; i++) {
            if (str.charAt(i) < '0' || str.charAt(i) > '9')
                break;
            res = res * 10 + str.charAt(i) - '0';
            if (ans > 0 && res > Integer.MAX_VALUE)
                return Integer.MAX_VALUE;
            if (ans < 0 && -res < Integer.MIN_VALUE)
                return Integer.MIN_VALUE;
        }
        return (int) res * ans;

    }
}



class DemoOffer67{
    public static void main(String[] args) {
        Offer67 o = new Offer67();
        String s =
                "    0000000000000   ";
        System.out.println("r="+o.strToInt(s));


    }
}